package com.shop.mall.servlet;

import com.alibaba.fastjson.JSONObject;
import com.shop.mall.dao.impl.BookDaoImpl;
import com.shop.mall.entity.Book;
import com.shop.mall.utils.BaseResultVO;
import com.shop.mall.utils.GetUUIDUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author admin
 * @version 1.0
 * @date 2019/4/23
 */
@WebServlet(urlPatterns = "/BookServlet")
public class BookServlet extends HttpServlet {
    private static final long serialVersionUID = -4312421151492117889L;
    private final Map<String, Object> cache = new HashMap<>();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String operation = request.getParameter("operation");
        if (operation != null) {
            switch (operation) {
                case "addBook":
                    addBook(request, response);
                    break;
                case "showAll":
                    showAll(request, response);
                    break;
                case "updateBook":
                    updateBook(request, response, request.getParameter("id"));
                    break;
                case "deleteBook":
                    deleteBook(request, response);
                    break;
                case "selectBookById":
                    selectBookById(request, response, request.getParameter("bookid"));
                    break;
                default:
                    break;
            }
        }
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    private void showAll(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("cpage");
        if (currentPage == null) {
            currentPage = "1";
        }
        BookDaoImpl bookDao = new BookDaoImpl();
        try {
            bookDao.showAll(Integer.parseInt(currentPage), 5);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void addBook(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        PrintWriter out = response.getWriter();
        BaseResultVO resultVO = new BaseResultVO();

        //String id = request.getParameter("id");
        String bookname = request.getParameter("bookname");
        String isbn = request.getParameter("isbn");
        String publisher = request.getParameter("publisher");
        String price = request.getParameter("price");
        String publisdate = request.getParameter("publisdate");
        if (StringUtils.isBlank(StringUtils.trim(bookname))
                || StringUtils.isBlank(StringUtils.trim(isbn))
                || StringUtils.isBlank(StringUtils.trim(publisher))
                || StringUtils.isBlank(StringUtils.trim(price))) {

            //按照put顺序展示
            JSONObject jsonObject = new JSONObject(true);
            jsonObject.put("id", GetUUIDUtil.getId());
            jsonObject.put("bookname", bookname);
            jsonObject.put("isbn", isbn);
            jsonObject.put("publisher", publisher);
            jsonObject.put("price", price);

            resultVO.setResult(false);
            resultVO.setCode(-1);
            resultVO.setData(JSONObject.toJSONString(jsonObject));
            resultVO.setMessage("参数缺失，请检查并填写数据");

            System.out.println("参数缺失，请检查并填写数据," + resultVO);
            out.println(resultVO);
            out.close();
            out.flush();
        }

        String bookId = String.valueOf(cache.get("id"));
        if ((bookId != null) && StringUtils.equals(bookId, GetUUIDUtil.getId())) {
            resultVO.setResult(false);
            resultVO.setCode(-1);
            resultVO.setData(JSONObject.toJSONString(bookId));
            resultVO.setMessage("图书ID已存在!,请勿重复添加");
            out.println(resultVO);
            out.close();
            out.flush();
        }
        cache.put("id", GetUUIDUtil.getId());
        BookDaoImpl bookDao = new BookDaoImpl();
        Book book = new Book();
        //TODO
        book.setId(Integer.parseInt(GetUUIDUtil.getId()));
        book.setBookname(bookname);
        book.setIsbn(isbn);
        book.setPrice(price);
        book.setPublisher(publisher);
        int line = bookDao.add(book);
        if (line > 0) {
            resultVO.setResult(true);
            resultVO.setCode(0);
            resultVO.setData(JSONObject.toJSONString(book));
            System.out.println("操作成功," + resultVO);
            //request.getRequestDispatcher("/pages/book/index.jsp").forward(request, response);
            response.sendRedirect(request.getContextPath() + "/pages/book/index.jsp");
        } else {
            resultVO.setResult(false);
            resultVO.setCode(-1);
            resultVO.setData(JSONObject.toJSONString(book));
            System.out.println("操作失败," + resultVO);
            response.sendRedirect(request.getContextPath() + "/pages/book/fail.jsp");
        }

    }

    private void updateBook(HttpServletRequest request, HttpServletResponse response, String id) {
        String bookname = request.getParameter("bookname");
        String isbn = request.getParameter("isbn");
        String publisher = request.getParameter("publisher");
        String price = request.getParameter("price");
        String publisdate = request.getParameter("publisdate");
        BookDaoImpl bookDao = new BookDaoImpl();
        try {
            int line = bookDao.update(Integer.parseInt(id), bookname, isbn, publisher, Integer.parseInt(price), publisdate);
            if (line > 0) {
                //请求重定向
                response.sendRedirect(request.getContextPath() + "/pages/book/index.jsp");
                return;
            }
            response.sendRedirect(request.getContextPath() + "/pages/book/fail.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void deleteBook(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        BookDaoImpl bookDao = new BookDaoImpl();
        int line;
        try {
            line = bookDao.delete(Integer.parseInt(id));
            if (line > 0) {
                //请求重定向
                response.sendRedirect(request.getContextPath() + "/pages/book/index.jsp");
                return;
            }
            response.sendRedirect(request.getContextPath() + "/pages/book/fail.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void selectBookById(HttpServletRequest request, HttpServletResponse response, String bookid) {
        //String id = request.getParameter("bookid");
        BookDaoImpl bookDao = new BookDaoImpl();
        try {
            List<Book> bookList = bookDao.select(Integer.parseInt(bookid));
            if (bookList != null && bookList.size() > 0) {
                //请求重定向
                response.sendRedirect(request.getContextPath() + "/pages/book/index.jsp");
                return;
            }
            response.sendRedirect(request.getContextPath() + "/pages/book/fail.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
